# coding=utf-8
from django.db import models
from django.db.models import signals
from django.dispatch import receiver


class Demo(models.Model):
    x = models.IntegerField()
    y = models.CharField(max_length=30, blank=True, null=True)

    def save(self, *args, **kwargs):
        print 'Demo on save() begin'
        super(Demo, self).save(*args, **kwargs)
        print 'Demo on save() end'

    def delete(self, *args, **kwargs):
        print 'Demo on delete() begin'
        super(Demo, self).delete(*args, **kwargs)
        print 'Demo on delete() end'

class Omed(models.Model):
    demo = models.ForeignKey('Demo')
    count = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        print 'Omed on save() begin'
        super(Omed, self).save(*args, **kwargs)
        print 'Omed on save() end'

    def delete(self, *args, **kwargs):
        print 'Omed on delete() begin'
        super(Omed, self).delete(*args, **kwargs)
        print 'Omed on delete() end'

@receiver(signals.pre_save)
def my_pre_save(sender, instance, using, **kwargs):
    if isinstance(instance, Demo): # if sender.__name__ == 'Demo':
        print 'my_pre_save()'
        print 'sender:', sender, '\ninstance:', instance, '\nusing:', using, '\nkwargs:', kwargs

@receiver(signals.post_save)
def my_post_save(sender, instance, using, **kwargs):
    if isinstance(instance, Demo): # if sender.__name__ == 'Demo':
        print 'my_post_save()'
        print 'sender:', sender, '\ninstance:', instance, '\nusing:', using, '\nkwargs:', kwargs
        o, is_new = Omed.objects.get_or_create(
            demo=instance,
            defaults={
                'count': instance.x + len(instance.y)
            }
        )
        print 'New Item:', is_new, '\nObject:', o, o.demo, o.count

@receiver(signals.pre_delete)
def my_pre_delete(sender, instance, using, **kwargs):
    if isinstance(instance, Demo): # if sender.__name__ == 'Demo':
        print 'my_pre_delete()'
        print 'sender:', sender, '\ninstance:', instance, '\nusing:', using, '\nkwargs:', kwargs
        instance.omed_set.all().delete()

@receiver(signals.post_delete)
def my_post_delete(sender, instance, using, **kwargs):
    if isinstance(instance, Demo): # if sender.__name__ == 'Demo':
        print 'my_post_delete()'
        print 'sender:', sender, '\ninstance:', instance, '\nusing:', using, '\nkwargs:', kwargs
